package {
	import Classes.pj_styles;
	
	import SEApp.se_app;
	
	import UIFree.uif_Timer;
	import UIFree.uif_loader;
	import UIFree.uif_styles;
	
	import UIUtils.uif_json;
	import UIUtils.uif_tb;
	import UIUtils.uif_utilBitmap;
	
	import api_servers.pi_myserver;
	import api_servers.pi_servers;
	
	import cardsbody.pi_multicard;
	import cardsbody.pi_pngcard;
	
	import com.adobe.images.PNGEncoder;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.BlendMode;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.external.ExternalInterface;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.text.TextField;
	import flash.utils.ByteArray;
	
	import templates.pi_templates1;
	
	public class _imgLoad extends se_app {
		private var _server: pi_myserver;
		private var _start: int;
		private var _count: int;
		private var _index: int;
		private var _group: int;
		private var _image: Bitmap;
		private var _info: TextField;
		private var _adata: Array;
		
		public function _imgLoad() {
			super(stage.stageWidth, stage.stageHeight);
			resetData();
			serversInit();
			initStartData();

//			loadTemplate(12473);
			
			_image = new Bitmap();
			_info = new TextField();
			_info.width = width;
			addChild(_image);
			addChild(_info);
			
			nextLoad();
		}
		
		protected function initStartData(): void {
			var id: int = stage.loaderInfo.parameters['id'];
			if (id) {
				for (var i: int=0; i<_adata.length; i++) {
					if (_adata[i].id >= id) {
						_start = i;
						break;
					}
				}
			} else _start = stage.loaderInfo.parameters['start'];
			_count = stage.loaderInfo.parameters['count'];
			
			_group = stage.loaderInfo.parameters['group']?stage.loaderInfo.parameters['group']:0;			
			_index = 0;
		}
		
		protected function resetData(): void {
			pi_data.resetData(pi_data.maskInfoList);
			pi_data.resetData(pi_templates1.maskInfoList);
			_adata = (pi_data.maskInfoList as Array).concat(pi_templates1.maskInfoList);
		}
		
		protected function nextLoad(): void {
			var mi: Object = _adata[_start + _index];
			_index++;
			if (_index <= _count) {
				if (mi.jpg && (mi.group == _group)) {
					loadTemplate(mi.id);
					uif_Timer.one(1000, function(e: Event): void {
						nextLoad();
					});
				} else {
					nextLoad();
				}
			}
		}
		
		
		protected function serversInit(): void {
			var storageURL: String = 'http://pj.1gb.ru/';
			pi_servers.ADDR 			= [storageURL, storageURL, storageURL, storageURL];
			pi_servers.MROOT_URL		= storageURL + 'pj/';
			pi_servers.PREVIEW_URL		= pi_servers.MROOT_URL + 'jpg_preview/';
			
			pi_myserver.MODEL_NAME = 'pjholes01';
			
			_server = new pi_myserver(this, storageURL + 'games/index.php');
		}
		
		override protected function getStyles():uif_styles {
			return new pj_styles();
		}
		
		protected function loadTemplate(id: int): void {
			var info: Object = pi_data.infoFromID(id);
			uif_utilBitmap.loadTransImage(pi_servers.MROOT_URL + 'JPG/' + id + '.jpg',
										pi_servers.MROOT_URL + 'JPG/' + id + 'm.jpg', new Bitmap(), 
										function(bmp: Bitmap): void {
											doTemplateLoad(bmp, info);
										}); 
		}
		
		protected function uploadHole(pngData: ByteArray, tmplId: int, holeId: int, bounds: Rectangle): void {
			var a_params: Array = [
				{pn:'querycount', pv: 1},
				{pn:'query1', pv: pi_myserver.MODEL_NAME + 
					';uploadHole;' + tmplId + ';' + holeId + ';' + 
								bounds.x + ',' + bounds.y + ',' + bounds.width + ',' + bounds.height} 
			];
			
			var header: URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
			var request: URLRequest = _server.createRequest(a_params, _server.api_url, URLRequestMethod.GET);
			request.method = URLRequestMethod.POST;
			request.requestHeaders.push(header);
			request.data 	= pngData;
			_server.jsrHelper(a_params, function(a_data: Object): void {
			}, '', false, '', request);
		}
		
		protected function doTemplateLoad(bmp: Bitmap, tmplInfo: Object): void {
			
			var spots: Array = uif_tb.searchSpots(bmp.bitmapData);
			var params: Object = {
				id: tmplInfo.id,
				holes: []
			}
			spots.forEach(function(item: Object, i: int, arr: Array): void {
				var size: Point = new Point(item.bounds.width, item.bounds.height);
				if (size.length > 80) {
					var spot: Bitmap = new Bitmap(item.spot);
					var mat: Matrix = new Matrix(1, 0, 0, 1, -item.bounds.x, -item.bounds.y);
					
					var result: BitmapData = new BitmapData(item.bounds.width, item.bounds.height, true, 0);
					result.fillRect(result.rect, 0xFF000000);
					result.draw(spot, null, null, BlendMode.ERASE);
					result.draw(bmp, mat, new ColorTransform(0, 0, 0));
					
					var png: ByteArray = PNGEncoder.encode(result);
					uploadHole(png, tmplInfo.id, i, item.bounds);
					
					params.holes.push([item.bounds.x, item.bounds.y, item.bounds.width, item.bounds.height]);
				}
			});
			
			if (_image.bitmapData) _image.bitmapData.dispose();
			_image.bitmapData = bmp.bitmapData;		

			if (params.holes.length > 0) {
				_server.oneQuery('holesInfo', tmplInfo.id + ';' + uif_json.e(params), function(a_data: Object): void {
				});
				
				_info.appendText(tmplInfo.id + ','); 
				trace(tmplInfo.id + ',');
			}
		}
	}
}